<template>
	<view class="report-page">
		<view class="report-reason">
			<view class="reason-title">举报理由</view>
			<view class="title-box">
				<text class="reason-desc">{{reasonTags.label}}</text>
				<uni-easyinput type="textarea" v-model="title" :inputBorder="false" autoHeight
					placeholder="可能有展示或隐晦的表达色情内容、诱导/暗示色情服务、暗示有性相关效果的商品等。"
					:placeholderStyle='"color: #999999;font-size:28rpx"'></uni-easyinput>
			</view>
		</view>
		<view class="reason-title" v-if="reasonTags && reasonTags.children && reasonTags.children.length > 0">
			<view class="detailed-title">举报内容</view>
			<view class="reason-tags">
				<view v-for="(tag, index) in reasonTags.children" :key="index" class="reason-tag"
					:class="{ active: selectedTags[0] === tag }" @click="toggleTag(tag)">
					{{ tag.label }}
				</view>
			</view>
		</view>
		<view class="reason-title">
			<view class="description-title">举报描述</view>
			<view class="input-container">
				<view class="input-with-upload">
					<uni-easyinput type="textarea" v-model="content" :inputBorder="false" autoHeight
						placeholder="请描述具体在哪些画面、文案、肢体动作、声音、私信等有展示或隐晦的表达色情相关内容"
						:placeholderStyle='"color: #999999;font-size:28rpx"'></uni-easyinput>

					<view class="upload-image">
						<view class="upload-btn" @click="chooseImage">
							<image :src="`${$ImgBaseUrl}report-camera.png`" class="upload-icon" />
							<text class='upload-text'>添加图片</text>
						</view>
						<!-- 图片预览容器：添加加载状态和背景层 -->
						<view class="image-preview-container" v-if="img">
							<!-- 浅色背景层（解决透明图片问题） -->
							<view class="image-bg"></view>
							<!-- 加载占位符（解决加载延迟显示黑色问题） -->
							<view class="loading-placeholder" v-if="!imageLoaded">
								<uni-icons type="spinner-cycle" size="24" color="#999" />
							</view>
							<!-- 图片元素：添加加载完成事件 -->
							<image :src="img" mode="aspectFill" class="preview-image" @load="imageLoaded = true">
							</image>
							<view class="delete-btn" @click.stop="deleteImage">
								<uni-icons type="closeempty" size="16" color="#F5F5F5"></uni-icons>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="btn-box">
			<button class="submit-btn" @click="submitReport">提交举报</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		watch
	} from 'vue';
	import {
		addReport
	} from '@/api/report.js'
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		qiNiuFileUpload
	} from '@/utils/qiniu.js';
	import {
		useStore
	} from 'vuex';
	const imageLoaded = ref(false);
	const store = useStore();
	// 详细理由标签
	const reasonTags = ref([]);
	// 选中的标签，改为单选后，数组最多存一个元素
	const selectedTags = ref([]);
	// 举报内容等
	const content = ref('')
	const img = ref('');
	const title = ref('')
	const tempImagePath = ref("");
	const type = ref(''); // 初始化为空，后续动态赋值
	const isLoading = ref(false);
	const reportData = ref(null); // 初始值为null

	onLoad((options) => {
		// 1. 接收并解析原有举报分类数据（item）
		if (options.item) {
			reasonTags.value = JSON.parse(decodeURIComponent(options.item));
			console.log('接收的举报类型数据:', reasonTags.value);
		}

		// 2. 接收并解析举报对象数据（jobData）
		if (options.item2) {
			try {
				reportData.value = JSON.parse(decodeURIComponent(options.item2));
				console.log('接收的举报对象数据:', reportData.value);
			} catch (error) {
				console.error('举报对象数据解析失败:', error);
				uni.showToast({
					title: '数据加载失败',
					icon: 'none'
				});
				// 解析失败时重置为安全的空对象，避免后续报错
				reportData.value = {};
			}
		} else {
			console.warn('未接收到举报对象数据');
			// 未接收到数据时设置为空对象，避免后续报错
			reportData.value = {};
		}
	});

	// 监听reportData变化，动态设置type
	watch(() => reportData.value, (newVal) => {
		// 确保newVal是对象（避免null/undefined）
		if (!newVal || typeof newVal !== 'object') {
			type.value = 'USER'; // 默认类型
			return;
		}

		// 根据不同字段动态设置type
		if ('busServiceResults' in newVal) {
			type.value = 'JOB';
		} else if ('info' in newVal) {
			type.value = 'PART_TIME_JOB';
		} else if ('serviceEvaluate' in newVal) {
			type.value = 'USER';
		} else {
			type.value = 'USER'; // 默认类型
			console.warn('未匹配到特定类型，使用默认类型USER');
		}

		console.log('动态设置的举报类型:', type.value);
	});

	// 切换标签选中状态，改为单选逻辑
	const toggleTag = (tag) => {
		if (selectedTags.value[0] === tag) {
			selectedTags.value = [];
		} else {
			selectedTags.value = [tag];
		}
	};

	// 选择图片（仅相册）
	const chooseImage = () => {
		openAlbum();
	};

	const openAlbum = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album'],
			success: (res) => {
				handleImageSuccess(res.tempFilePaths[0]);
			},
			fail: (err) => {
				console.error('选择图片失败:', err);
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				});
			}
		});
	};

	const handleImageSuccess = (tempFilePath) => {
		if (tempFilePath) {
			imageLoaded.value = false;
			uni.showLoading({
				title: '处理中...',
				mask: true
			});

			tempImagePath.value = tempFilePath;
			img.value = tempFilePath;

			compressImage(tempFilePath).then(compressedPath => {
				img.value = compressedPath;
				uni.hideLoading();
			}).catch(err => {
				console.log('压缩失败，使用原图', err);
				uni.hideLoading();
			});
		}
	};

	// 图片压缩
	const compressImage = (src) => {
		return new Promise((resolve, reject) => {
			uni.compressImage({
				src,
				quality: 70,
				success: (res) => {
					resolve(res.tempFilePath);
				},
				fail: reject
			});
		});
	};

	// 上传图片到七牛云
	const uploadImageToQiNiu = async () => {
		if (!tempImagePath.value) {
			return '';
		}

		const userId = store.state.userInfo?.id || 'defaultUserId';
		const timestamp = Date.now();
		const random = Math.floor(Math.random() * 10);
		const key = `images/servitem/${userId}/${timestamp}_${random}.png`;

		const files = [{
			path: tempImagePath.value,
			key: key
		}];

		return new Promise((resolve, reject) => {
			qiNiuFileUpload(files,
				(successUrl) => {
					console.log('七牛返回URL', successUrl);
					const imageUrl = successUrl.split(',')[0];
					resolve(imageUrl);
				},
				(error) => {
					console.error('七牛上传失败', error);
					reject(error);
				}
			);
		});
	};

	// 删除图片
	const deleteImage = () => {
		img.value = '';
		tempImagePath.value = '';
	};

	// 提交举报
	const submitReport = async () => {
		// 基础表单校验
		if (!title.value.trim()) {
			return uni.showToast({
				title: '请填写举报理由',
				icon: 'none'
			});
		}
		if (reasonTags.value.children && reasonTags.value.children.length > 0 && selectedTags.value.length === 0) {
			return uni.showToast({
				title: '请选择至少一个举报内容',
				icon: 'none'
			});
		}
		if (!content.value.trim()) {
			return uni.showToast({
				title: '请填写举报描述',
				icon: 'none'
			});
		}

		// 校验reportData是否有效（必须是对象）
		// if (!reportData.value || typeof reportData.value !== 'object') {
		// 	return uni.showToast({
		// 		title: '举报对象数据异常',
		// 		icon: 'none'
		// 	});
		// }

		// 校验type是否有效
		// if (!type.value) {
		// 	return uni.showToast({
		// 		title: '举报类型获取失败',
		// 		icon: 'none'
		// 	});
		// }

		try {
			isLoading.value = true;
			let imageUrl = '';
			if (tempImagePath.value) {
				imageUrl = await uploadImageToQiNiu();
			}

			// 根据type动态设置reportId（核心修改：添加多层安全校验）
			let reportId = '';
			if (type.value === 'USER') {
				// 安全获取userId：先判断reportData.value是否存在，再访问userId
				reportId = reportData.value?.userId || '';
			} else {
				// 安全获取userInfo.id：先判断reportData.value是否存在，再判断userInfo是否存在，最后访问id
				reportId = reportData.value?.userInfo?.id || '';
			}

			// 验证reportId是否存在
			// if (!reportId) {
			// 	throw new Error('未获取到有效的举报对象ID');
			// }

			const reportParams = {
				reportId: reportId,
				content: content.value.trim(),
				categoryId: selectedTags.value.length > 0 ?
					selectedTags.value.map(tag => tag.id).join(',') : '',
				img: imageUrl,
				type: type.value,
				title: title.value
			};

			const res = await addReport(reportParams);

			if (res.code === 200) {
				uni.showToast({
					title: '举报提交成功',
					icon: 'success'
				});
				// 提交成功后返回上一页
				uni.navigateTo({
					url: `/pages/reportCenter/reportProgress?id=${res.data.id}`
				})
			} else {
				uni.showToast({
					title: res.msg || '提交失败，请重试',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('举报提交失败:', error);
			uni.showToast({
				title: error.message || '网络异常，请稍后重试',
				icon: 'none'
			});
		} finally {
			isLoading.value = false;
		}
	};
</script>
<style lang="scss" scoped>
	.report-page {
		padding: 20rpx;
		background: #F5F5F5;
		height: 100vh;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;

		.report-reason {
			margin-bottom: 32rpx;

			.reason-title {
				font-size: 24rpx;
				color: #666;
				font-weight: 400;
				margin-bottom: 20rpx;
				margin-left: 26rpx;
			}

			.title-box {
				display: flex;
				flex-direction: column;
				background: #FFFFFF;
				border-radius: 20rpx;
				padding: 20rpx;
				box-sizing: border-box;
			}

			.reason-desc {
				font-size: 30rpx;
				font-weight: 400;
				color: #303133;
				margin-bottom: 12rpx;
			}
		}

		.reason-title {
			font-size: 24rpx;
			color: #666;
			font-weight: 400;

			.detailed-title {
				font-size: 24rpx;
				color: #666;
				font-weight: 400;
				margin-bottom: 20rpx;
				margin-left: 26rpx;

				.no-data {
					background: #FFFFFF;
					border-radius: 20rpx;
					padding: 40rpx 20rpx;
					text-align: center;
					font-size: 28rpx;
					color: #999999;
					margin-bottom: 20rpx;
				}
			}

			.reason-tags {
				display: flex;
				flex-wrap: wrap;
				background: #FFFFFF;
				border-radius: 20rpx;
				margin-bottom: 20rpx;
				padding: 20rpx 20rpx 0rpx 20rpx;
				box-sizing: border-box;

				.reason-tag {
					border-radius: 6rpx;
					height: 70rpx;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
					font-size: 28rpx;
					font-weight: 400;
					color: #333;
					background: #F1F1F1;
					display: flex;
					justify-content: center;
					align-items: center;
					padding: 0rpx 20rpx;

					&.active {
						background: #E5F0FF;
						color: #2F80ED;
					}
				}
			}
		}

		.reason-title {
			font-size: 24rpx;
			color: #666;
			font-weight: 400;

			.description-title {
				font-size: 24rpx;
				color: #666;
				font-weight: 400;
				margin-bottom: 20rpx;
				margin-left: 26rpx;
			}
		}

		.input-container {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 20rpx;
			box-sizing: border-box;
		}

		.input-with-upload {
			position: relative;
			min-height: 530rpx;
		}

		.upload-image {
			position: absolute;
			left: 20rpx;
			bottom: 20rpx;
			z-index: 10;
			margin-bottom: 0;
			display: flex;
			align-items: center;

			.image-preview-container {
				position: relative;
				width: 160rpx;
				height: 160rpx;
				margin-top: 16rpx;
				border-radius: 8rpx;
				overflow: hidden;
				/* 1. 容器添加浅色背景，避免加载前显示黑色 */
				background-color: #f5f5f5;
			}

			.image-bg {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background-color: #ffffff;
				z-index: 1; // 背景在图片下方
			}

			.preview-image {
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
				position: relative;
				z-index: 2; // 图片在背景上方
			}

			.loading-placeholder {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: #f5f5f5;
				z-index: 3; // 占位符在最上层
			}

			.upload-btn {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				width: 115rpx;
				height: 115rpx;
				border: 1rpx dashed #cfcfcf;
				border-radius: 10rpx;
				background: #fff;
				margin-right: 20rpx;

				.upload-text {
					color: #999999;
					font-weight: 400;
					font-size: 22rpx;
				}

				.upload-icon {
					width: 32rpx;
					height: 29rpx;
					margin-bottom: 8rpx;
				}
			}


			.delete-btn {
				position: absolute;
				top: -3rpx;
				right: 0rpx;
				width: 40rpx;
				height: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				z-index: 20;
			}
		}
	}

	.btn-box {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;
		background: #ffffff;
		height: 166rpx;

		.submit-btn {
			background: #2F80ED;
			color: #fff;
			border-radius: 44rpx;
			font-size: 30rpx;
			height: 88rpx;
			font-weight: 500;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
		}
	}

	::v-deep .uni-easyinput__content {
		border-radius: 20rpx;
	}
</style>